package com.northchurchcolumbus.podcast.ncpodcaster;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Map;

import com.northchurchcolumbus.podcast.ncpodcaster.Uploader.UploaderProgressListener;

public class NCPodcaster
{
    private File podcastInput;
    private File artwork;
    private Calendar date;
    private String title;
    private String speaker;
    private Map<String,String> ctx;
    private File podcastOutput;
    private String podcastOutputFilename;
    ID3Tagger tagger;
    MP3Encoder encoder = new LameEncoder();
    Uploader uploader = new FTPUploader();
    PodPoster poster = new BloggerPodPoster();

    
    public NCPodcaster(Map<String,String> ctx, File inputFile, int month, int day, int year, String title, String speaker) throws Exception
	{
        date = Calendar.getInstance();
        date.set(year, month-1, day, 0, 0);
        init(ctx, inputFile, date, title, speaker);
	}

    public NCPodcaster(Map<String,String> ctx, File inputFile, Calendar date, String title, String speaker) throws Exception
    {
        init(ctx, inputFile, date, title, speaker);
    }

    private void init(Map<String, String> ctx, File inputFile, 
            Calendar date, String title, String speaker) throws IOException
    {
        this.podcastInput = inputFile;
        if(!podcastInput.isFile() || !podcastInput.canRead())
        {
            throw new IOException("File: " + podcastInput.getAbsolutePath() + " cannot be read.");
        }

        this.date = date;
        this.title = title;
        this.speaker = speaker;
        this.ctx = ctx;
        String dateFormat = String.format("%1$tY%1$tm%1$td", date);
        podcastOutput =  File.createTempFile(dateFormat, ".mp3");
        podcastOutput.deleteOnExit();
        podcastOutputFilename = dateFormat + ".mp3";
        tagger = new JaudioID3Tagger(podcastInput);

        URL artworkFileURL=this.getClass().getResource("/Picture.jpeg");

        InputStream is =artworkFileURL.openStream();
        artwork = File.createTempFile("artwork", "jpeg");
        artwork.deleteOnExit();
        OutputStream artworkFileOutput = new FileOutputStream(artwork);
        byte[] bytes = new byte[1024];
        int bread = -1;
        while((bread=is.read(bytes))>=0)
        {
            artworkFileOutput.write(bytes, 0, bread);
        }
        artworkFileOutput.close();
        is.close();


        
    }

    public void upload(UploaderProgressListener listener, boolean deleteExistingFile) throws Exception
    {
        update("Uploading");
        uploader.upload(podcastOutput, "content", podcastOutputFilename, ctx, listener, deleteExistingFile);
        
        update("Finished uploading, verifying URL");
        URL podhttp = new URL(ctx.get("urlPrefix") + podcastOutputFilename);
        URLConnection conn = podhttp.openConnection();
        conn.getHeaderField(0);
        if(conn.getContentLength()<=0)
        {
            throw new IOException("The podcast URL: " + podhttp.toExternalForm() + " could not be reached.");
        }
    }

    public void publish(boolean isDraft) throws Exception 
    {
        update("Verified.  Posting Blog Entry.");
        poster.post(title, speaker, date, new URL(ctx.get("urlPrefix") + podcastOutputFilename), ctx, isDraft);
        update("Done Posting.");
    }
    
    public void tag() throws Exception
    {
        update("Tagging");
        ID3Tagger outputTagger = new JaudioID3Tagger(podcastOutput);
        outputTagger.setTags( artwork, title, date);
    }
    public void encode() throws Exception
    {
		if(podcastOutput.exists())
		{
		    podcastOutput.delete();
		}
		
		if(tagger.getBitrate()>24)
		{
	        update("Encoding");
		    encoder.encode(podcastInput, podcastOutput, ctx);
		}    
	}

    public static void update(String state)
    {
        System.out.println("---> " + state);
    }

}
